package pay

import (
	"context"
	"fmt"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
	"gitee.com/bobo-rs/innovideo-services/library/models"
	"gitee.com/bobo-rs/innovideo-services/library/services/pay/paypal"
	"github.com/gogf/gf/v2/container/gvar"
)

type (
	// Services 支付服务
	Services struct {
		registerPay map[string]IPay
	}

	// IPay 服务接口
	IPay interface {
		// Payment 支付
		Payment(ctx context.Context, tradeNo string, amount float64, other interface{}) (response interface{}, err error)
		// Notify 支付回调
		Notify(ctx context.Context, f func(ctx context.Context, payNo, tradeNo, event string, arg ...interface{}) error) (*models.PayNotifyResponse, error)
		// Config 支付配置
		Config(config map[string]*gvar.Var) error
		// ConfirmPayment 确认支付-PayPal支付必须
		ConfirmPayment(ctx context.Context, payNo string) (*models.ConfirmPayResponse, error)
	}
)

func New() *Services {
	return &Services{
		registerPay: map[string]IPay{
			`paypal`: &paypal.SPayPal{},
		},
	}
}

// Register 注册服务
func (s *Services) Register(ctx context.Context, driver string) IPay {
	payHandler, ok := s.registerPay[driver]
	if !ok {
		panic(fmt.Sprintf(`%s service not in  forgot register?`, driver))
	}

	// 获取配置
	r, err := service.Config().GetGroupVar(ctx, driver)
	if err != nil {
		panic(err)
	}

	// 设置支付配置
	//fmt.Println(r.MapStrVar())
	err = payHandler.Config(r.MapStrVar())
	if err != nil {
		panic(err)
	}
	return payHandler
}
